package com.gxuwz.stats.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.ResearchProject;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.ResearchProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/userResearchProject")
public class ResearchProjectUserController {

    @Autowired
    private ResearchProjectService researchProjectService;

    /**
     * 分页查询
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/reProUserList")
    public ResponseEntity<Map<String, Object>> reProUserList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {
            System.out.println("收到的查询集："+params);
            // 提取 Token
            String token = authorization.replace("Bearer ", "");
//            System.out.println("Received Token: " + token);

// 解析 Token 获取当前用户ID（假设使用 JWT）
            JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
            int userId = jwtTokenUtil.getUserIdFromToken(token); // 自定义工具类解析Token
//            System.out.println("Token解析="+userId);

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<ResearchProject> page = new Page<>(currentPage, pageSize);
            QueryWrapper<ResearchProject> queryWrapper = new QueryWrapper<>();

            // 添加当前用户ID条件
//            queryWrapper.eq("user_id", params.get("userId"));
// 强制添加当前用户ID条件
            queryWrapper.eq("user_id", userId);

            // 模糊查询条件 - 项目名称
            if (params.containsKey("projectName") && params.get("projectName") != null && !params.get("projectName").isEmpty()) {
                queryWrapper.like("project_name", params.get("projectName"));
            }

            // 模糊查询条件 - 项目类别
            if (params.containsKey("projectCategory") && params.get("projectCategory") != null && !params.get("projectCategory").isEmpty()) {
                queryWrapper.like("project_category", params.get("projectCategory"));
            }

            // 精确查询条件 - 项目状态
            if (params.containsKey("projectStatus") && params.get("projectStatus") != null && !params.get("projectStatus").isEmpty()) {
                queryWrapper.eq("project_status", params.get("projectStatus"));
            }

// 精确查询条件 - 项目年度
            if (params.containsKey("projectYear") && params.get("projectYear") != null && !params.get("projectYear").isEmpty()) {
                queryWrapper.eq("project_year", params.get("projectYear"));
            }

            // 调用 service 层的分页查询方法
            IPage<ResearchProject> resultPage = researchProjectService.getReProListWithUserInfo(page, queryWrapper);
//            IPage<ResearchProject> resultPage = researchProjectService.page(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增
     */
    @PostMapping("/addResearchProject")
    public ResponseEntity<Map<String, Object>> addResearchProject(@RequestBody ResearchProject researchProject) {
        System.out.println("===" + researchProject);

        researchProjectService.save(researchProject);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "新增成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改
     * @param researchProject
     * @return
     */
    @PutMapping("/editResearchProject")
    public ResponseEntity<Map<String, Object>> editResearchProject(@RequestBody ResearchProject researchProject) {
        System.out.println("user::" + researchProject);
        researchProjectService.updateById(researchProject);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }


}
